import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import * as jwt from 'jsonwebtoken';
import { ConfigService } from '@nestjs/config';
import { WINSTON_LOGGER_TOKEN } from 'src/winston/winston.module';

@Injectable()
export class EmailService {
  constructor(
    private readonly mailerService: MailerService,
    private configService: ConfigService,
  ) {}

  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;

  async sendEmailCode(data: {
    email: string;
    subject?: string;
    sign?: string;
  }) {
    try {
      const code = Math.random().toString().slice(-6);
      const date = new Date()
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replace(/\//g, '年')
        .replace(/\//g, '月')
        .replace(/,/g, '日')
        .replace(/:/g, ':');
      const sendMailOptions: ISendMailOptions = {
        to: data.email,
        subject: data.subject || '用户邮箱验证',
        template: 'validate.code.ejs', //这里写你的模板名称，如果你的模板名称的单名如 validate.ejs ,直接写validate即可 系统会自动追加模板的后缀名,如果是多个，那就最好写全。
        //内容部分都是自定义的
        context: {
          code, //验证码
          date, //日期
          sign: data.sign || '系统邮件,回复无效。', //发送的签名,当然也可以不要
        },
        // attachments: [
        //     {
        //         filename: 'validate.code.ejs', //文件名
        //         path: path.join(process.cwd(), './src/email/template/validate.code.ejs') //服务端的文件地址
        //     }
        // ]
      };
      this.mailerService
        .sendMail(sendMailOptions)
        .then(() => {
          this.logger.log(
            `发送邮件给:${data.email},成功!主题:${data.subject || '默认'}`,
            `${EmailService.name}-${this.sendEmailCode.name}`,
          );
        })
        .catch((error) => {
          console.log(error);
          
          this.logger.error(
            `发送邮件给:${data.email}出错!主题:${data.subject || '默认'}`,
            `${EmailService.name}-${this.sendEmailCode.name}`,
          );
        });
      const secretKey = this.configService.get('SECRET', 'yssyyds');
      const token = jwt.sign({ code }, secretKey, { expiresIn: '30m' }); // 设置有效期10分钟
      return token;
    } catch (error) {
      this.logger.error(
        `发送邮件出错:${error}`,
        `${EmailService.name}-${this.sendEmailCode.name}`,
      );
      throw new BadRequestException('邮件发送失败！');
    }
  }
}
